/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.blacklist;

import com.elcom.emocbc.blacklist.dao.BlacklistDao;
import com.elcom.util.Constant;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Set;
import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class BlacklistParser implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(BlacklistParser.class);
    private BlacklistFileHandler blacklistFileHandler;

    public BlacklistParser(BlacklistFileHandler blacklistFileHandler) {
        this.blacklistFileHandler = blacklistFileHandler;
    }

    @Override
    public void run() {
        try {
            logger.debug(">>> Start checking blacklist from DB");
            BlacklistDao blacklistDao = BlacklistDao.getInstance();

            Set<String> newBlacklists;
            try {
                newBlacklists = blacklistDao.findAll();
//                logger.debug("Found {} msisdn in DB", newBlacklists.size());
            } catch (Exception ex) {
                logger.error("Unable to get blacklist from DB", ex);
                return;
            }

            if (blacklistFileHandler.currentBlacklist.size() != newBlacklists.size()) {
                logger.debug("Blacklist in DB: {}. Blacklist in file: {}. Overriding blacklist file...", newBlacklists.size(), blacklistFileHandler.currentBlacklist.size());
                blacklistFileHandler.currentBlacklist = newBlacklists;
                updateBlacklist();
            } else {
                Iterator<String> currentIterator = blacklistFileHandler.currentBlacklist.iterator();
                Iterator<String> newIterator = newBlacklists.iterator();
                boolean isDifferent = false;
                while (currentIterator.hasNext()) {
                    if (!currentIterator.next().equals(newIterator.next())) {
                        isDifferent = true;
                        break;
                    }
                }
                
                if (isDifferent) {
                    blacklistFileHandler.currentBlacklist = newBlacklists;
                    updateBlacklist();
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    private void updateBlacklist() {
        try {
            blacklistFileHandler.updateBlacklistToFile();
            logger.debug("Blacklist file updated");

            Configuration config = ConfigurationManager.getConfiguration(Constant.SYS_CONFIG_NAME);
            String[] reloadConfigCommand = config.getArray("reloadConfigCommand", new String[]{"smsg_xcore", "reload", "routing_rule"}, "general");
            ProcessBuilder processBuilder = new ProcessBuilder(reloadConfigCommand);
            processBuilder.start();
            logger.debug("Smsgate Xcore config reloaded");
        } catch (Exception ex) {
            logger.error("Update blacklist failed", ex);

            try {
                //revert modification
                blacklistFileHandler.restoreBackupFile();
                logger.debug("Blacklist file restored");
            } catch (IOException ex1) {
                logger.error("", ex1);
            }
        }
    }
}
